<?php

/*
 * Object/Employe.php
 */

namespace RHX\Model\Object;

use Zend\Db\Adapter\Adapter;

class Employe {

    public $matricule;
    public $site_id;
    public $nom1;
    public $nom2;
    public $prenom;
    public $telephone;
    public $email;
    public $contrat_debut;
    public $contrat_fin;
    public $contrat_type;
    public $contrat_motif_depart;
    public $contrat_file;
    public $avenant_id;
    public $civil_id;
    public $situation_id;
    public $enfant;
    public $naissance;
    public $naissance_lieu;
    public $naissance_pays;
    public $nationalite_id;
    public $adresse1;
    public $cp1;
    public $ville1;
    public $adresse2;
    public $cp2;
    public $ville2;
    public $sejour_id;
    public $sejour_num;
    public $sejour_num_file;
    public $sejour_fin;
    public $cpam;
    public $pole_emploi;
    public $mutuelle;
    public $mutuelle_date_effet;
    public $rib;
    public $rib_iban;
    public $rib_bic;
    public $transport_id;
    public $vehicule;
    public $immatriculation;
    public $num_permis;
    public $sante_id;
    public $code_caisse_tcpos;
    public $cv_path;
    public $photo;
    public $actif;
    public $ancien;
    public $indice;
    public $transfert;

    /**
     * Adapteur de base de données
     * 
     * @var Adapter
     */
    protected $adapter;

    public function __construct(Adapter $adapter, $data = array()) {
	$this->adapter = $adapter;
	$this->exchangeArray($data);
    }

    public function exchangeArray($data) {
	$this->matricule		 = isset($data['matricule']) ? $data['matricule'] : null;
	$this->site_id			 = isset($data['site_id']) ? $data['site_id'] : 0;
	$this->nom1			 = isset($data['nom1']) ? $data['nom1'] : '';
	$this->nom2			 = isset($data['nom2']) ? $data['nom2'] : '';
	$this->prenom			 = isset($data['prenom']) ? $data['prenom'] : '';
	$this->telephone		 = isset($data['telephone']) ? $data['telephone'] : '';
	$this->email			 = isset($data['email']) ? $data['email'] : '';
	$this->contrat_debut		 = isset($data['contrat_debut']) ? $data['contrat_debut'] : '0000-00-00';
	$this->contrat_fin		 = isset($data['contrat_fin']) ? $data['contrat_fin'] : '0000-00-00';
	$this->contrat_type		 = isset($data['contrat_type']) ? $data['contrat_type'] : 0;
	$this->contrat_motif_depart	 = isset($data['contrat_motif_depart']) ? $data['contrat_motif_depart'] : 0;
	$this->contrat_file		 = isset($data['contrat_file']) ? $data['contrat_file'] : '';
	$this->avenant_id		 = isset($data['avenant_id']) ? $data['avenant_id'] : 0;
	$this->civil_id			 = isset($data['civil_id']) ? $data['civil_id'] : 0;
	$this->situation_id		 = isset($data['situation_id']) ? $data['situation_id'] : 0;
	$this->enfant			 = isset($data['enfant']) ? $data['enfant'] : 0;
	$this->naissance		 = isset($data['naissance']) ? $data['naissance'] : '0000-00-00';
	$this->naissance_lieu		 = isset($data['naissance_lieu']) ? $data['naissance_lieu'] : '';
	$this->naissance_pays		 = isset($data['naissance_pays']) ? $data['naissance_pays'] : '';
	$this->nationalite_id		 = isset($data['nationalite_id']) ? (int) $data['nationalite_id'] : 0;
	$this->adresse1			 = isset($data['adresse1']) ? $data['adresse1'] : '';
	$this->cp1			 = isset($data['cp1']) ? $data['cp1'] : '';
	$this->ville1			 = isset($data['ville1']) ? $data['ville1'] : '';
	$this->adresse2			 = isset($data['adresse2']) ? $data['adresse2'] : '';
	$this->cp2			 = isset($data['cp2']) ? $data['cp2'] : '';
	$this->ville2			 = isset($data['ville2']) ? $data['ville2'] : '';
	$this->sejour_id		 = isset($data['sejour_id']) ? $data['sejour_id'] : 0;
	$this->sejour_num		 = isset($data['sejour_num']) ? $data['sejour_num'] : '';
	$this->sejour_num_file		 = isset($data['sejour_num_file']) ? $data['sejour_num_file'] : '';
	$this->sejour_fin		 = isset($data['sejour_fin']) ? $data['sejour_fin'] : '0000-00-00';
	$this->cpam			 = isset($data['cpam']) ? $data['cpam'] : '';
	$this->pole_emploi		 = isset($data['pole_emploi']) ? $data['pole_emploi'] : '';
	$this->mutuelle			 = isset($data['mutuelle']) ? $data['mutuelle'] : '';
	$this->mutuelle_date_effet	 = isset($data['mutuelle_date_effet']) ? $data['mutuelle_date_effet'] : '';
	$this->rib			 = isset($data['rib']) ? $data['rib'] : '';
	$this->rib_iban			 = isset($data['rib_iban']) ? $data['rib_iban'] : '';
	$this->rib_bic			 = isset($data['rib_bic']) ? $data['rib_bic'] : '';
	$this->transport_id		 = isset($data['transport_id']) ? $data['transport_id'] : 0;
	$this->vehicule			 = isset($data['vehicule']) ? $data['vehicule'] : '';
	$this->immatriculation		 = isset($data['immatriculation']) ? $data['immatriculation'] : '';
	$this->num_permis		 = isset($data['num_permis']) ? $data['num_permis'] : '';
	$this->code_caisse_tcpos	 = isset($data['code_caisse_tcpos']) ? $data['code_caisse_tcpos'] : 0;
	$this->cv_path			 = isset($data['cv_path']) ? $data['cv_path'] : '#';
	$this->photo			 = isset($data['photo']) ? $data['photo'] : '#';
	$this->actif			 = isset($data['actif']) ? (int) $data['actif'] : 1;
	$this->ancien			 = isset($data['ancien']) ? (int) $data['ancien'] : 0;
	$this->indice			 = isset($data['indice']) ? (int) $data['indice'] : 0;
	$this->transfert		 = isset($data['transfert']) ? (int) $data['transfert'] : 0;
    }

    public function getArrayCopy() {
	return get_object_vars($this);
    }

    /**
     * @param string $date
     * @return Poste
     */
    public function getPoste($date = null) {
	// Table Poste
	$posteTable = new \RHX\Model\Table\PosteTable($this->adapter);

	// Avenant
	$avenant = $this->getAvenant($date);

	// Poste
	$poste = $posteTable->get($avenant->poste_id);

	return $poste;
    }

    /**
     * Avenant
     * 
     * @param string $date
     * @return Avenant
     */
    public function getAvenant($date = null) {
	$avenantTable	 = new \RHX\Model\Table\AvenantTable($this->adapter);
	$avenant	 = null;
	if (!is_null($date)) {
	    try {
		$avenant = $avenantTable->getAvenantByDate($this->matricule, $date);
	    }
	    catch (Exception $ex) {
		$avenant = $avenantTable->get($this->avenant_id);
	    }
	}
	if (is_null($avenant)) {
	    $avenant = $avenantTable->get($this->avenant_id);
	}
	return $avenant;
    }
    
    /**
     * Dernier avenant ou NULL
     * 
     * @return Avenant
     */
    public function getTheLastAvenant(){
        $historyTable = new \RHX\Model\Table\AvenantHistoryTable($this->adapter);
        $history = $historyTable->getByMatricule($this->matricule);
        $h = $history->current();
        if(!$h){
            foreach($history as $hs){
                if($hs){
                    return $hs->getAvenant();
                }
            }
            return NULL;
        }else{
            $h->getAvenant();
        }
    }

    /*  recupére l'avenant correspondant au contrat initial via l' instance Employe
     */

    public function getAvenantInitial() {
	$avenantHistoryTable	 = new \RHX\Model\Table\AvenantHistoryTable($this->adapter);
	$avenantTable		 = new \RHX\Model\Table\AvenantTable($this->adapter);

	$hitoryInit = $avenantHistoryTable->getInitialByMatricule($this->matricule);

	return $avenantTable->get($hitoryInit->avenant_id);
    }

    /**
     * Disponibilité
     *
     * @return EmployeDisponibilite
     */
    public function getDisponibilite() {
	// Table Disponibilité
	$disponibiliteTable = new \RHX\Model\Table\EmployeDisponibiliteTable($this->adapter);

	return $disponibiliteTable->getDispoByEmploye($this->matricule);
    }

    /**
     * Site
     *
     * @param $date
     * @return Site
     */
    public function getSite($date = null) {
	$avenant = $this->getAvenant($date);

	return $avenant->getSite();
    }

    /**
     * Historique des Avenants
     * 
     * @param string $order Ordre d'affichage
     * @return AvenantHistory
     */
    public function getAvenantHistory($order = 'avenant_id DESC') {
	// Table AvenantHistory
	$avenantHistoryTable = new \RHX\Model\Table\AvenantHistoryTable($this->adapter);

	$history = $avenantHistoryTable->getByMatricule($this->matricule, $order);
	$return	 = null;
	if ($history->count() > 1) {
	    $return = $history;
	}
	else {
	    $return = array();
	}
	//var_dump($history);

	return $return;
    }

    /**
     * Récupérer tous les avenants d'un employé dans l'ordre du premier au dernier
     * 
     * @param string $order Ordre d'affichage
     * @return array
     */
    public function getAvenants($order = 'avenant_id DESC') {
	$history	 = $this->getAvenantHistory($order);
	$avenants	 = array();
	foreach ($history as $h) {
	    $avenants[] = $h->getAvenant();
	}
	return $avenants;
    }

    /**
     * Type de Contrat
     * 
     * @return ContratType
     */
    public function getContratType() {
	// Table Type de contrat
	$typeTable = new \RHX\Model\Table\ContratTypeTable($this->adapter);

	return $typeTable->get($this->contrat_type);
    }

    /**
     * Titre de Transport
     * 
     * @return Transport
     */
    public function getTransport() {
	// Table Transport
	$transportTable = new \RHX\Model\Table\TransportTable($this->adapter);

	return $transportTable->get($this->transport_id);
    }

    /**
     * Retourner le Motif de Départ
     * 
     * @return Motif
     */
    public function getMotif() {
	// Table
	$motifTable = new \RHX\Model\Table\MotifTable($this->adapter);

	return $motifTable->get($this->contrat_motif_depart);
    }

    /**
     * Récupérer le Coefficient de l'employé
     * 
     * @return float
     */
    public function getCoefficient() {
	$type = $this->getContratType();

	return floatval($type->coef);
    }

    /**
     * Récupérer le Taux Horaire en cours
     * 
     * @param string $date
     * @return float
     */
    public function getTaux($date = null) {
	$avenant = $this->getAvenant($date);

	return floatval($avenant->taux);
    }

    /**
     * Tous les diplomes
     *
     * @return array
     */
    public function getDiplomes() {
	$table		 = new \RHX\Model\Table\EmployeDiplomeTable($this->adapter);
	$diplomes	 = null;
	try {
	    $diplomes = $table->getByMatricule($this->matricule);
	}
	catch (\Exception $ex) {
	    $diplomes = array();
	}

	return $diplomes;
    }

    /**
     * Tous les Formations
     * 
     * @return array
     */
    public function getFormations() {
	$table		 = new \RHX\Model\Table\EmployeFormationTable($this->adapter);
	$formations	 = null;
	try {
	    $formations = $table->getByMatricule($this->matricule);
	}
	catch (\Exception $ex) {
	    $formations = array();
	}

	return $formations;
    }

    /**
     * Ancienneté
     *
     * @param boolean $month Affichage du nombre en mois
     * @return int | string
     */
    public function getAnciennete($full = false) {
	$contratDebut	 = new \DateTime($this->contrat_debut);
	$maintenant	 = new \DateTime();

	$diff = date_diff($contratDebut, $maintenant);

	$value = 0;

	if ($diff) {
	    $signe = 1;
	    if ($diff->invert == 1) {
		$signe = -1;
	    }
	    else {
		$signe = 1;
	    }
	    if ($full) {
		$an	 = ($diff->y > 0) ? $diff->y . ' an(s)' : '';
		$mois	 = $diff->m . ' mois';
		$jour	 = $diff->d . ' jour(s)';
		$value	 = "$an $mois $jour";
	    }
	    else {
		$value = $signe * $value;
	    }
	}

	return $value;
    }

    /**
     * Valeur de l'ancienneté
     * 
     * @param boolean $show
     * @return float
     */
    public function getAncienneteValue($show = false) {
	$contratDebut	 = new \DateTime($this->contrat_debut);
	$maintenant	 = new \DateTime();
	$diff		 = date_diff($contratDebut, $maintenant);
	$value		 = 0.0;
	if ($diff) {
	    $signe	 = ($diff->invert == 1) ? -1 : 1;
	    $value	 = floatval($diff->y);
	    $mois	 = (int) $diff->m;
	    $mois += (int) $diff->d > 0 ? 1 : 0;
	    if ($mois >= 12) {
		$value++;
		$mois -= 12;
	    }
	    $moisValue	 = $mois / 12;
	    $value		 = $signe * ($value + $moisValue);
	}

	return ($show) ? number_format($value, 2, ',', ' ') : $value;
    }

    /**
     * Nombre de jour disponible pendant la semaine
     *
     * @param boolean $cp Indique si on doit appliquer la règle des congés payés
     * @return int
     */
    public function getNbJourDispo($cp = false) {
	// table EmployeDispo
	$dispoTable	 = new \RHX\Model\Table\EmployeDisponibiliteTable($this->adapter);
	$dispo		 = $dispoTable->getDispoByEmploye($this->matricule);
	$nbJour		 = 0;
	if ((int) $dispo->lundi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->mardi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->mercredi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->jeudi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->vendredi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->samedi == 1) {
	    $nbJour++;
	}
	if ((int) $dispo->dimanche == 1) {
	    $nbJour++;
	}

	if ($cp == true && $nbJour > 5) {
	    $nbJour = 5;
	}

	return $nbJour;
    }

    /**
     * Récupérer le Contrat Horaire Hebdomadaire d'un employé
     * 
     * @param bool $french
     * @param string $date
     * @return float|string
     */
    public function getHoraireHebdo($french = false, $date = null) {
	$avenant = $this->getAvenant($date);
	$hebdo	 = floatval($avenant->hebdo);
	if ($french) {
	    $hebdo = number_format($hebdo, 2, ',', ' ');
	}

	return $hebdo;
    }

    /**
     * Récupérer les heures non planifiées durant une période à partir d'une date appartenant
     *
     * @param string $date
     * @return string
     */
    public function getHeureNonPlanifiePeriode($date) {
	// Table Période
	$periodeTable		 = new \RHX\Model\Table\PeriodeTable($this->adapter);
	// Période correspondant à la date
	$periodeData		 = $periodeTable->getPeriodeByDate($date);
	$periode		 = new Periode($periodeData);
	// Table Planning Semaine
	$planningTable		 = new \RHX\Model\Table\PlanningSemaineTable($this->adapter);
	$heureNonPlannifie	 = '00:00';
	try {
	    $floatVal		 = $planningTable->getHeureNonPlanifie($periode, $this->matricule);
	    //var_dump($floatVal);
	    $heureNonPlannifie	 = \RHX\Helper\RHDateTime::toTime(number_format($floatVal, 2, ',', ''));
	}
	catch (\Exception $ex) {
	    throw $ex;
	}

	return $heureNonPlannifie;
    }

    /**
     * Données sur les Congées Payé
     * 
     * @param string $date
     * @return array
     */
    public function getDataCP($date = null) {
	$date = is_null($date) ? date('Y-m-d') : $date;
	$hebdo	 = $this->getHoraireHebdo();
	$nbJour	 = $this->getNbJourDispo(true);
	$heureCP = 0;
	if ($nbJour != 0) {
	    $heureCP = $hebdo / $nbJour;
	}
	$paye	 = 0.0;
	$taux	 = $this->getTaux($date);
	$coef	 = $this->getCoefficient();
	$paye	 = $heureCP * $taux * $coef;
	$heure	 = \RHX\Helper\RHDateTime::toTime($heureCP);

	return array(
	    'paye'		 => $paye,
	    'heure'		 => $heure,
	    'heureFloat'	 => $heureCP,
	    'coef'		 => $coef,
	    'taux'		 => $taux,
	    'hebdo'		 => $hebdo,
	    'nb'		 => $nbJour,
	);
    }

    /**
     * Titre de séjour
     * 
     * @return TitreSejour
     */
    public function getTitreSejour() {
	// table type de séjour
	$typeSejourTable = new \RHX\Model\Table\TitreSejourTable($this->adapter);

	return $typeSejourTable->get($this->sejour_id);
    }

    /**
     * Mutuelle
     *
     * @return Mutuelle
     */
    public function getMutuelle() {
	// Table Mutuelle
	$mutuelleTable = new \RHX\Model\Table\MutuelleTable($this->adapter);

	return $mutuelleTable->get($this->mutuelle);
    }

    /**
     * Le(s) visite(s) médicale(s)
     * 
     * @return EmployeSante | array
     */
    public function getVisiteMedicale($all = false) {
	// Table visite
	$santeTable	 = new \RHX\Model\Table\EmployeSanteTable($this->adapter);
	$matricule	 = $this->matricule;

	$rows = $santeTable->select(function(\Zend\Db\Sql\Select $select) use($matricule) {
	    $where = new \Zend\Db\Sql\Where();
	    $where->equalTo('matricule', $matricule);
	    $select->where($where);
	    $select->order('date_visite DESC');
	});

	if ($all) {
	    return $rows;
	}
	else {
	    return $rows->current();
	}
    }

    /**
     * Entretien
     * 
     * @param type $all
     * @return EmployeEntretien
     */
    public function getEntretien($all = false) {
	$tableEntretien	 = new \RHX\Model\Table\EmployeEntretienTable($this->adapter);
	$matricule	 = $this->matricule;
	//\Zend\Debug\Debug::dump($matricule, 'Matricule employé');
	$rows		 = $tableEntretien->select(function(\Zend\Db\Sql\Select $select)use($matricule) {
	    $where = new \Zend\Db\Sql\Where();
	    $where->equalTo('matricule', $matricule);
	    $select->where($where);
	    $select->order('date_entretien DESC');
	    //\Zend\Debug\Debug::dump($select->getSqlString(), 'SQL');
	});
	if ($all) {
	    return $rows;
	}
	else {
	    return $rows->current();
	}
    }

    /**
     * Liste des planning type de l'employé
     *
     * @return \Zend\Db\ResultSet\ResultSet
     */
    public function getTemplates($obsolete = false) {
	// table employe template
	$tableTemplate	 = new \RHX\Model\Table\EmployeTemplateTable($this->adapter);
	$matricule	 = $this->matricule;

	return $tableTemplate->select(function(\Zend\Db\Sql\Select $select)use($matricule, $obsolete) {
		    $where = new \Zend\Db\Sql\Where();
		    $where->equalTo('matricule', $matricule);
//	    if(!$obsolete){
//		$where->equalTo('actif', 1);
//	    }else{
//		$where->equalTo('actif', 0);
//	    }
		    $select->where($where);
		});
    }

    /**
     * Adapteur de base de données
     * 
     * @return Adapter
     */
    public function getAdapter() {
	return $this->adapter;
    }

    /**
     * Retourne le matricule de l'employé
     * @param boolean $print Si à true affiche le matricule interne de l'employé avec l'indice
     * @return int | string
     */
    public function getMatricule($print = false) {
	$mat = ((int)$this->transfert <= 0) ? $this->matricule : $this->getOriginalMatriculeFromTransfert($this);
	if ($print == true) {
	    if ($this->ancien != 0 && $this->indice != 0) {
		$mat .= "(<sup>{$this->indice}</sup>)";
	    }
	}

	return $mat;
    }

    /**
     * Nationalité
     * 
     * @return Nationalite
     */
    public function getNationalite() {
	$table		 = new \RHX\Model\Table\NationaliteTable($this->adapter);
	$nationalite	 = $table->get($this->nationalite_id);

	return $nationalite;
    }

    /**
     * Récupérer l'ancien contrat de l'employé
     * 
     * @return Employe
     */
    public function getOld() {
	$tableEmploye = new \RHX\Model\Table\EmployeTable($this->adapter);
	try {
	    $oldEmploye = $tableEmploye->get($this->ancien);

	    return $oldEmploye;
	}
	catch (\Exception $ex) {
	    return null;
	}
    }

    /**
     * Taux horaire chargé
     * 
     * @param string $date
     * @param boolean $print
     * @param boolean $round
     * @param int $precision
     * @return real|string
     */
    public function getTauxCharge($date = null, $print = false, $round = false, $precision = 2) {
	$charge = $this->getTaux($date) * $this->getCoefficient();
	if ($print) {
	    if ($round) {
		return number_format(round($charge, $precision), $precision, ',', ' ');
	    }
	    else {
		return number_format($charge, $precision, ',', ' ');
	    }
	}
	elseif ($round) {
	    return round($charge, $precision);
	}
	return $charge;
    }

    /* determine si un date donnée est compris dans la durée du contrat de l'employe
     * @param string $day 
     */

    public function isDayInContrat($day) {
	$jour = new \RHX\Helper\RHDateTime($day);

	$dateEntree	 = new \RHX\Helper\RHDateTime($this->contrat_debut);
	$hasDateDepart	 = $this->contrat_fin != null && $this->contrat_fin !== '' && $this->contrat_fin !== '0000-00-00';
	$dateDepart	 = $hasDateDepart ? new \RHX\Helper\RHDateTime($this->contrat_fin) : null;

	$bDayIsBetween = ($dateEntree->isLT($jour) || $dateEntree->isEqual($jour) ) && (!$hasDateDepart || ($dateDepart->isGT($jour) || $dateDepart->isEqual($jour) ) );

	return $bDayIsBetween;
    }

    /**
     * Récupération du matricule original
     * 
     * @param \RHX\Model\Object\Employe $employe
     * @return int
     */
    private function getOriginalMatriculeFromTransfert(Employe $employe){
	//echo '<pre>Matricule : ' .$employe->matricule .' Transfert : ' .$employe->transfert .'</pre>';
	if((int)$employe->transfert == 0 || (int)$employe->transfert == -9999){
	    return (int)$employe->matricule;
	}
	$tableEmploye = new \RHX\Model\Table\EmployeTable($this->getAdapter());
	$employe = $tableEmploye->get($employe->transfert);
	return $this->getOriginalMatriculeFromTransfert($employe);
    }
    
    /* Détermine si l'employé est transféré ou pas 
     * 
     * @return boolean 
     */
    public function isTransfered(){
        return (boolean) ($this->transfert  < 0); 
    }
    
    /* Recupère le site  de destination d'un employé tranferé
     */
    public function getDestinationSite(){
        $matricule = $this->matricule;
        
        $tableEmploye   = new \RHX\Model\Table\EmployeTable($this->getAdapter());
        $tableSite      = new \RHX\Model\Table\SiteTable($this->getAdapter());
        $employeDest = $tableEmploye->getOneByTransfert($matricule);
        
        return $tableSite->get($employeDest->site_id);
        
    }
}

?>
